<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <!-- model 用来指定，表单采集到的数据，要同步的哪个对象中 -->
    <!-- rules 用来指定，当前表单的验证规则对象 -->
    <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="100px">
      <!-- 通过 prop 指定校验规则 -->
      <el-form-item label="登录名称" prop="username">
        <el-input v-model="userForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'UserInfo',
  data() {
    return {
      // 表单的数据对象
      /* userForm: {
        username: this.$store.state.userinfo.username,
        nickname: this.$store.state.userinfo.nickname,
        email: this.$store.state.userinfo.email
      }, */
      // 对象的浅拷贝 Object.assign()
      userForm: Object.assign({}, this.$store.state.userinfo),
      // 表单的验证规则对象
      userFormRules: {
        nickname: [
          { required: true, message: '用户昵称是必填项', tigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称必须是1-10位的非空字符', tigger: 'blur' }
        ],
        email: [{ type: 'email', required: true, message: '用户邮箱格式不正确', tigger: 'blur' }]
      }
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      // 每次重置，都把 store 中最新的值取出来，赋值给 userForm
      this.userForm = Object.assign({}, this.$store.state.userinfo)
      // this.$refs.userFormRef.resetFields()
    },
    // 点击按钮，修改用户的基本信息
    updateUserInfo() {
      // 1. 对表单进行预校验
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return
        // 2. 请求接口，修改用户的基本信息
        const { data: res } = await this.$http.put('/my/userinfo', this.userForm)
        if (res.code !== 0) return this.$message.error('更新用户信息失败！')

        // 更新成功，提示用户，并调用 action 函数，刷新用户信息
        this.$message.success('更新用户信息成功！')
        this.$store.dispatch('initUserInfo')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
